import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
import 'package:yp/Xwidgets/bottom_sheet.dart';
import 'package:yp/config/index.dart';
import 'package:yp/config/style.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';
import 'package:yp/widgets/index.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import '../../helper.dart';
import '../../router.dart';
// import 'dart:js' as js;

import 'package:yp/pages/address_selector/address_model.dart';

class JoinGroup extends StatefulWidget {
  const JoinGroup({Key key}) : super(key: key);

  @override
  _JoinGroupState createState() => _JoinGroupState();
}

class _JoinGroupState extends State<JoinGroup>
    with SingleTickerProviderStateMixin {
  Map detail;
  bool isBackApp = true;
  var timer;
  var seconds;
  var countContent;
  var usr_limit = 0;
  var tmlNumIds = '';
  Map<String, dynamic> _groupInfoMap = {
    'join': 1,
    'need': 3,
    'list': [
      {'leader': true, 'member': true},
      {'member': false},
      {'member': false}
    ]
  };

  @override
  void initState() {
    if (kIsWeb == true) {
      var islog = getQueryVariable('login');
      print('是否登录');
      print(islog);
      if (islog == '1') {
        tmlNumIds = getQueryVariable('tml_num_id');
        print(tmlNumIds);
        isBackApp = false;
        getInfo(tmlNumIds);
        return;
      }
      if (Get.arguments != null) {
        tmlNumIds = Get.arguments['tml_num_id'];
        getInfo(tmlNumIds);
      } else {
        tmlNumIds = getQueryVariable('tml_num_id');
        Get.offAllNamed(RouteConfig.mallLogin,
            arguments: {'tml_num_id': tmlNumIds});
      }
    } else {
      if (Get.arguments == null) {
        tmlNumIds = SpUtil.getString('tml_num_id');
      } else {
        tmlNumIds = Get.arguments['tml_num_id'];
      }

      getInfo(tmlNumIds);
    }
    print('22222');
    super.initState();
  }

  //时间格式化，根据总秒数转换为对应的 hh:mm:ss 格式
  Map constructTime(int mss) {
    int days = (mss / (60 * 60 * 24)).floor();
    int hours = ((mss % (60 * 60 * 24)) / (60 * 60)).floor();
    int minutes = ((mss % (60 * 60)) / 60).floor();
    int seconds = (mss % 60).floor();
    print(days.toString() +
        "天" +
        hours.toString() +
        "小时" +
        minutes.toString() +
        "分钟" +
        seconds.toString() +
        "秒");
    return {'hours': hours, "minutes": minutes, 'seconds': seconds};
  }

  void startTimer() {
    const period = const Duration(seconds: 1);
    timer = Timer.periodic(period, (timer) {
      if (seconds <= 0) {
        //倒计时秒数为0，取消定时器
        print('我被取消了');
        timer.cancel();
        // getData();
      }
      setState(() {
        countContent = date_format(seconds);
        seconds--;
      });
    });
  }

  date_format(micro_second) {
// 总秒数
    var second = (micro_second).floor();
// 天数
    var day = (second / 3600 / 24).floor();
// 小时
    var hr = (second / 3600 % 24).floor();
// 分钟
    var min = (second / 60 % 60).floor();
// 秒
    var secs = (second % 60).floor();

    return day.toString() +
        "天" +
        hr.toString() +
        "时" +
        min.toString() +
        "分" +
        secs.toString() +
        '秒';
  }

  getInfo(tmlNumIds) {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var params = {'tml_num_id': tmlNumIds};
      print('开团支付完成');
      print(params);
      Api.assembledetail(params).listen((event) {
        if (event['code'] == 0) {
          var params2 = {
            "data_sign": 0,
            "channel_num_id": 99,
            "use_platform": 3,
            "tml_num_id": tmlNumIds,
            "g_buy_id": event['detail']['g_buy_id'],
            // "shop_id": SpUtil.getInt('storeShopNum'),
            "shop_id": 102002001,

            "prv_num_id": addressInfo['prv_num_id'],
            "city_num_id": addressInfo['city_num_id'],
            "city_area_num_id": addressInfo['city_area_num_id'],
            "town_num_id": addressInfo['town_num_id'],
            "maplocation_x": addressInfo['maplocation_x'],
            "maplocation_y": addressInfo['maplocation_y'],
            'norm_num_id': null,
            "access_token": SpUtil.getString('token'),
          };
          print("state.group_buy_item.runtimeType.toString()");
          print(params2);
          Api.groupDetail(params2).listen((event) {
            if (event['code'] == 0) {
              usr_limit = int.parse(event['group_buy_item']['usr_limit']);
            }
          });
          seconds = (event['detail']['over_time_millisecond'] / 1000).floor();
          startTimer();
          setState(() {
            detail = event['detail'];
          });
        }
      });
    });
  }

  @override
  void dispose() async {
    super.dispose();
    timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: YPNavigationBar(
          '参团详情',
          onPressed: () {
            if (isBackApp) {
              Get.back();
            } else {
              Get.offAllNamed(RouteConfig.main);
            }
          },
        ),
        body: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
                child: Column(children: [
              if (detail != null) _goodsInfo(),
              SizedBox(height: 10),
              if (detail != null) _groupInfo(),
              SizedBox(height: 20),
              _groupRule()
            ]))
          ],
        ));
  }

  /// 商品信息
  Widget _goodsInfo() {
    return GestureDetector(
      onTap: () {
        /// 查看商品详情
      },
      child: Container(
        padding: const EdgeInsets.all(10),
        color: EsColors.White,
        child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
          CachedImage(
              width: 130,
              height: 130,
              margin: EdgeInsets.fromLTRB(0, 10, 8, 12),
              scale: BoxFit.cover,
              path: detail['image_default_id']),
          SizedBox(width: 6),
          Expanded(
            child: SizedBox(
              height: 145,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text(
                    detail['g_buy_style_name'],
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: EsColors.TitleSecondary,
                        fontSize: EsSizes.SM,
                        fontWeight: EsFontWeights.Normal),
                  ),
                  Padding(
                      padding: const EdgeInsets.only(top: 2, bottom: 6),
                      child: Text('此商品正在参加拼团',
                          style: TextStyle(
                              fontSize: EsSizes.SM,
                              color: EsColors.Primary,
                              fontWeight: EsFontWeights.Normal))),
                  Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Container(
                                decoration: BoxDecoration(
                                    border: Border.all(
                                        color: EsColors.Primary, width: 1),
                                    borderRadius: BorderRadius.circular(10)),
                                child: Padding(
                                    padding:
                                        const EdgeInsets.fromLTRB(3, 0, 3, 0),
                                    child: Text(
                                      detail['g_buy_size'].toString() + '人团',
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          color: EsColors.Primary,
                                          fontSize: EsSizes.XXS,
                                          fontWeight: EsFontWeights.Normal),
                                    ))),
                            SizedBox(width: 10),
                            // Text(
                            //   '已团${ detail['g_buy_size']}件',
                            //   maxLines: 1,
                            //   overflow: TextOverflow.ellipsis,
                            //   style: TextStyle(
                            //       color: EsColors.ContentSecondary,
                            //       fontSize: EsSizes.XXS,
                            //       fontWeight: EsFontWeights.Normal),
                            // ),
                          ],
                        ),
                        RichText(
                            text: TextSpan(children: [
                          TextSpan(
                              text: '￥${detail['g_buy_price'].toString()}',
                              style: TextStyle(
                                  fontSize: EsSizes.XL,
                                  color: EsColors.Primary,
                                  fontWeight: EsFontWeights.SemiBold)),
                          // TextSpan(text: '￥${detail['price']}', style: TextStyle(fontSize: EsSizes.XS, decoration: TextDecoration.lineThrough, color: EsColors.ContentSecondary, fontWeight: EsFontWeights.Normal)),
                        ])),
                      ]),
                ],
              ),
            ),
          ),
        ]),
      ),
    );
  }

  /// 团信息
  Widget _groupInfo() {
    return Container(
      color: EsColors.White,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          _tipsInfo(),
          Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
            SizedBox(width: 50),
            Wrap(
                spacing: (MediaQuery.of(context).size.width -
                        140 -
                        80 * (-1 + detail['g_buy_size'] ?? 0)) /
                    (detail['g_buy_size'] ?? 0),
                children: List.generate(
                    detail['g_buy_size'], (index) => _member(index))),
            SizedBox(width: 50),
          ]),
          _invite(),
          SizedBox(height: 24)
        ],
      ),
    );
  }

  ///拼团提示信息
  Widget _tipsInfo() {
    if (detail['g_buy_size'] == detail['g_buy_join_size']) {
      // 拼团成功
      return Container(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
        child: RichText(
            textAlign: TextAlign.center,
            text: TextSpan(children: [
              TextSpan(
                  text: '恭喜您，拼团成功啦！',
                  style: TextStyle(
                      fontSize: EsSizes.SM,
                      color: EsColors.Primary,
                      fontWeight: EsFontWeights.Medium)),
            ])),
      );
    } else if (detail['g_buy_join_size'] <= detail['g_buy_size']) {
      // 正在拼团
      return Container(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
        child: RichText(
            textAlign: TextAlign.center,
            text: TextSpan(children: [
              TextSpan(
                  text: '还差',
                  style: TextStyle(
                      fontSize: EsSizes.SM,
                      color: EsColors.TitleSecondary,
                      fontWeight: EsFontWeights.Normal)),
              TextSpan(
                  text: (detail['g_buy_size'] - detail['g_buy_join_size'])
                          ?.toString() ??
                      '0',
                  style: TextStyle(
                      fontSize: EsSizes.XL,
                      color: EsColors.Primary,
                      fontWeight: EsFontWeights.SemiBold)),
              TextSpan(
                  text: '人即可组团成功，',
                  style: TextStyle(
                      fontSize: EsSizes.SM,
                      color: EsColors.TitleSecondary,
                      fontWeight: EsFontWeights.Normal)),
              TextSpan(
                  text: countContent,
                  style: TextStyle(
                      fontSize: EsSizes.SM,
                      color: EsColors.Primary,
                      fontWeight: EsFontWeights.SemiBold)),
              TextSpan(
                  text: '后结束',
                  style: TextStyle(
                      fontSize: EsSizes.SM,
                      color: EsColors.TitleSecondary,
                      fontWeight: EsFontWeights.Normal))
            ])),
      );
    } else {
      ///
      return SizedBox();
    }
  }

  /// 团内信息
  Widget _member(index) {
    return GestureDetector(
      onTap: () {
        bool isgo = true;
        detail['usr_info_models'].forEach((element) {
          if (element['user_num_id'] == SpUtil.getInt('empeNumId')) {
            toast('你已经在团里');
            isgo = false;
            return;
          }
        });

        if (SpUtil.getInt('is_new_user') != 1 && usr_limit == 1) {
          toast('此团面向新人团');
          isgo = false;
          return;
        }
        // var request=js.context.callMethod("onBridgeReady",[1,2,3,4,5,6]);
        print('去支付');
        if (isgo) {
          Get.toNamed(RouteConfig.groupSettleAccounts, arguments: {
            'supply_unit_num_id': '',
            'g_buy_norm_num_id': detail['g_buy_norm_num_id'],
            'shop_id': detail['ec_shop_num_id'],
            "item_num_id": detail['item_num_id'],
            "g_buy_id": detail['g_buy_id'],
            "style_num_id": '',
            "ec_style_num_id": '',
            'shopnum': 1
          });
        }

        // if (info['member'] ?? false) {
        //   print('查看信息');
        // } else {
        //   setState(() {
        //     info['member'] = true;
        //     _groupInfoMap['join'] += 1;
        //   });
        // }
      },
      child: Stack(
        children: [
          SizedBox(
            width: 70,
            height: 70,
          ),
          Positioned(
              width: 60,
              height: 60,
              child: Image.asset(
                  (index < detail['usr_info_models'].length)
                      ? 'assets/images/group_mumber.png'
                      : 'assets/images/group_wait_mumber.png',
                  fit: BoxFit.fill)),
          Positioned(
              bottom: 4,
              left: 18,
              child: Visibility(
                visible: true,
                child: Container(
                    decoration: BoxDecoration(
                        color: EsColors.Primary,
                        borderRadius: BorderRadius.circular(8)),
                    padding: EdgeInsets.fromLTRB(4, 1, 4, 1),
                    child: Text(
                        (index < detail['usr_info_models'].length &&
                                detail['usr_info_models'][index]['is_header'] ==
                                    1)
                            ? '团长'
                            : '团员',
                        style: TextStyle(
                            color: EsColors.White,
                            fontSize: EsSizes.XXS,
                            fontWeight: EsFontWeights.Normal))),
              ))
        ],
      ),
    );
  }

  /// 邀请拼团按钮
  Widget _invite() {
    return Visibility(
      visible: _groupInfoMap['join'] != _groupInfoMap['need'],
      child: Column(children: [
        SizedBox(height: 20),
        Text('组团成功后尽快为您发货',
            style: TextStyle(
                fontSize: EsSizes.SM,
                color: EsColors.ContentSecondary,
                fontWeight: EsFontWeights.Normal)),
        SizedBox(height: 10),
        TextButton(
            onPressed: () {
              print('邀请参加团');
              var shareUrl;
              shareUrl = Config.H5_URL +
                  '&isInvite=true&isGroups=1&gbuyid=' +
                  detail['g_buy_id'].toString();
              YpBottomSheet.showShareGift(context, (selectIndex, selectString,
                  {info, list}) {
                var model = fluwx.WeChatShareWebPageModel(
                  shareUrl,
                  title: '邀请拼团',
                  description: '邀请拼团',
                  thumbnail: fluwx.WeChatImage.network(
                      detail['image_default_id'] != null
                          ? detail['image_default_id']
                          : ''),
                  scene: selectIndex == 0
                      ? fluwx.WeChatScene.SESSION
                      : fluwx.WeChatScene.TIMELINE,
                );
                fluwx.shareToWeChat(model);
              }, title: '邀请好友');
              // setState(() {
              //   for (var item in _groupInfoMap['list']) {
              //     if (item['member'] == false) {
              //       item['member'] = true;
              //       _groupInfoMap['join'] += 1;
              //       return;
              //     }
              //   }
              // });
            },
            child: Text(
              '邀人来参团',
              style: TextStyle(
                  color: EsColors.White,
                  fontSize: EsSizes.LG,
                  fontWeight: EsFontWeights.Medium),
            ),
            style: OutlinedButton.styleFrom(
                // 去除放大点击区域
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                minimumSize: Size(0, 0),
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 56),
                primary: EsColors.Primary,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(23)),
                backgroundColor: EsColors.Primary)),
      ]),
    );
  }

  /// 拼团规则
  Widget _groupRule() {
    return Container(
      color: EsColors.White,
      padding: EdgeInsets.symmetric(vertical: 12, horizontal: 10),
      child: Row(
        children: [
          Text('拼团规则',
              style: TextStyle(
                  fontSize: EsSizes.SM,
                  color: EsColors.Content,
                  fontWeight: EsFontWeights.Normal)),
          SizedBox(width: 24),
          Expanded(
            child: GestureDetector(
              onTap: () {},
              child: Row(
                children: [
                  Expanded(
                    child: Text('参团或开团-人满发货-人不满退货',
                        // textAlign: TextAlign.end,
                        style: TextStyle(
                            fontSize: EsSizes.SM,
                            color: EsColors.TitleSecondary,
                            fontWeight: EsFontWeights.Normal)),
                  ),
                  SizedBox(width: 4),
                  // Icon(
                  //   Icons.arrow_forward_ios,
                  //   size: EsSizes.SM,
                  //   color: EsColors.ContentSecondary,
                  // )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
